import { useCallback } from 'react';
import { useFlowStore } from '../store/flowStore';

/**
 * 键盘快捷键处理 Hook
 * 处理删除节点和边的快捷键（Backspace/Delete）
 */
export function useKeyboardShortcuts() {
  const { nodes, edges, setNodes, setEdges } = useFlowStore();

  const handleKeyDown = useCallback(
    (event: React.KeyboardEvent) => {
      // 检查是否按下了 Backspace 或 Delete 键
      if (event.key === 'Backspace' || event.key === 'Delete') {
        // 过滤出当前选中的节点和边
        const selectedNodes = nodes.filter((node) => node.selected);
        const selectedEdges = edges.filter((edge) => edge.selected);

        // 如果有选中的节点或边
        if (selectedNodes.length > 0 || selectedEdges.length > 0) {
          // 阻止默认的浏览器行为（如在某些输入框中按 Backspace 会导致页面后退）
          event.preventDefault();

          // 删除选中的节点及其关联的边
          if (selectedNodes.length > 0) {
            const nodeIdsToDelete = new Set(selectedNodes.map((node) => node.id));
            // 过滤掉被删除的节点
            const remainingNodes = nodes.filter((node) => !nodeIdsToDelete.has(node.id));
            setNodes(remainingNodes);

            // 过滤掉与被删除节点相关的边
            const remainingEdges = edges.filter(
              (edge) =>
                !nodeIdsToDelete.has(edge.source) && !nodeIdsToDelete.has(edge.target)
            );
            setEdges(remainingEdges);
          }

          // 删除选中的边（如果边本身被选中）
          if (selectedEdges.length > 0) {
            const edgeIdsToDelete = new Set(selectedEdges.map((edge) => edge.id));
            // 过滤掉被删除的边
            const remainingEdges = edges.filter(
              (edge) => !edgeIdsToDelete.has(edge.id)
            );
            setEdges(remainingEdges);
          }
        }
      }
    },
    [nodes, edges, setNodes, setEdges]
  );

  return { handleKeyDown };
}

